import {messages, simplifyDataSource} from "share/common";
import React from 'react'
import { connect } from 'react-redux'
import { Radio, Button } from 'antd';
import moment from 'moment'
import FeedbackManagementService from 'containers/setting/feedback-management/feedback-management.service'
import feedbackService from 'containers/feedback/feedback.service';
import AdvancedTable from 'components/advanced-table'
import menuRoute from 'routes/menuRoute';
import Feedback from '../../feedback/feedback';
const { SimpleTable } = AdvancedTable;

const statusMap = {
  '-1': messages('common.all')/*全部*/,
  '0': messages('basic-4.key1')/*待处理*/,
  '1': messages('basic-4.key2')/*受理中*/,
  '2': messages('basic-4.key3')/*等待回复*/,
  '3': messages('basic-4.key4')/*已解决*/,
  '99': messages('basic-4.key5')/*已关闭*/
}

class CustomerFeedbackList extends React.Component {
  constructor(props) {
    super(props);

    this.state = {
      loading: false,
      feedbackModalVisible: false,
      data: [],
      searchParams:{},
      searchForm: [
        { id: 'feedbackNo', dataIndex: "feedbackNo", label: messages('basic-4.key21')/*流水号*/, component: 'Input',},
        { id: 'keyword', dataIndex: "issueContent", label: messages('basic-4.key42')/*反馈内容*/, component: 'Input', },
        {
          id: 'dateRange', label: messages('basic-4.key25')/*提交时间*/, component: 'DateRangePicker',
          dataIndex: 'createdDate',
          props: {
            placeholder: messages('basic-4.key48')/*请选择temp*/,
          },
          parser: value => ({
            startDate: (value && value[0]) ? value[0].utc().format() : null,
            endDate: (value && value[1]) ? value[1].utc().format() : null
          })
        },
        {
          id: 'status',
          label: messages('common.column.status')/*状态*/,
          dataIndex: 'status',
          component:
            <Radio.Group>
              {
                Object.keys(statusMap).map(item => <Radio value={item}>{statusMap[item]}</Radio>)
              }
            </Radio.Group>,
        }
      ],
      columns: [],
    }
  }

  componentWillMount() {
    this.renderDataSource();
  };

  renderDataSource = () => {
    let dataSource = [
      {feedbackNo: messages('basic-4.key21')/*流水号*/, width: 140},
      {modules: messages('basic-4.key22')/*模块*/, width: 140, render: text => text ? text.map(item=>item.name).join(',') : "-"},
      {issueContent: messages('basic-4.key42')/*反馈内容*/, width: 500},
      {tags: messages('common.label')/*标签*/, width: 140, render: text => text ? text.map(item=>item.name).join(',') : "-"},
      {clients: messages('basic-4.key23')/*渠道*/, width: 140, render: text =>  text ? text.map(item=>item.name).join(',') : "-"},
      {status: messages('common.column.status')/*状态*/, width: 100, render: text => text ? statusMap[text] : '-'},
      {createdDate: messages('basic-4.key25')/*提交时间*/, width: 140, render: text => text ? moment(text).format("YYYY-MM-DD") : null},
    ];
    let columns = simplifyDataSource(dataSource);

    this.setState({
      columns
    }, () => {
      this.renderSearchForm();
    })
  };

  renderSearchForm = () => {
    const {searchForm} = this.state;
    feedbackService.getIssueItems({codes: ['MODULE', 'TAG', 'CHANNEL']}).then(res => {
      if(res.data){
        let json = {
          MODULE: {
            id: 'moduleIds',
            label: messages('basic-4.key22')/*模块*/,
            dataIndex: 'modules',
          },
          CHANNEL: {
            id: 'clientIds',
            label: messages('basic-4.key23')/*渠道*/,
            dataIndex: 'clients',
          },
          TAG: {
            id: 'tagIds',
            label: messages('common.label')/*标签*/,
            dataIndex: 'tags',
          }
        };

        let arr = [];
        for(let attr in res.data){
          arr.push(
            {
              id: json[attr].id,
              label: json[attr].label,
              dataIndex: json[attr].dataIndex,
              component:
                <Radio.Group>
                  {
                    res.data[attr].map(item => <Radio value={item.id}>{item.name}</Radio>)
                  }
                </Radio.Group>,
            }
          )
        }
        this.setState({ searchForm: searchForm.concat(arr) });
      }
    })
  };

  service = (page, size, searchParams) => {
    let params = Object.assign({page, size}, searchParams);
    this.setState({ searchParams });
    for (let paramsName in params) {
      !params[paramsName] && delete params[paramsName];
    }
    if (params.status === '-1') {
      delete params.status;
    } else {
      params.states = params.status;
      delete params.status;
    }
    return FeedbackManagementService.getFeedbackList(params)
      .then((response) => {
        return response;
      })
  };

  editItem = (e, record) => {
    this.context.router.push(menuRoute.getPageUrlByKey("customer-feedback-detail-personal").replace(':id', record.id));
  };

  afterClose = () => {
    this.advancedTableRef.getList()
  };

  closeFeedback = () => {
    this.setState({feedbackModalVisible: false}, ()=>{
      this.advancedTableRef.getList()
    })
  };

  render() {
    const { searchForm, columns, feedbackModalVisible } = this.state;
    return (
      <div className="feedback-management">
        {
          searchForm.length >= 6 &&
          <div className="full-height-page">
            <SimpleTable
              onRef={ref => this.advancedTableRef = ref}
              title={messages('basic-4.key49')/*反馈管理*/}
              searchForm={searchForm}
              columns={columns}
              tableName={'feedback-management-table'}
              show={['table-utils']}
              service={this.service}
              onRow={record => ({onClick: (e) => {this.editItem(e, record)}})}
              rowKey="id"
            >
              <Button type='primary' onClick={()=>{this.setState({feedbackModalVisible: true})}}>
                {messages('basic-4.key56')/*新建反馈*/}
              </Button>
            </SimpleTable>
          </div>
        }
        {
          feedbackModalVisible && (
            <Feedback hideScreenShot onClose={this.closeFeedback} />)
        }
      </div>
    )
  }
}

CustomerFeedbackList.contextTypes = {
  router: React.PropTypes.object
};

function mapStateToProps(state) {
  return {
    company: state.login.company,
    main: state.main,
    authToken: state.main.authToken,
    tenantMode: state.main.tenantMode,
    user: state.login.user,
    menuPermission: state.main.menuPermission,
  }
}

export default connect(mapStateToProps)(CustomerFeedbackList);
